package com.rybbaby.tss.front.tssStudent.controller;

import com.google.common.collect.ImmutableMap;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.consts.RoleConsts;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.core.web.service.IViewService;
import com.rybbaby.tss.front.tssAllocation.entity.TssAllocation;
import com.rybbaby.tss.front.tssAllocation.service.ITssAllocationService;
import com.rybbaby.tss.front.tssMealFee.entity.TssMealFee;
import com.rybbaby.tss.front.tssMealFee.service.ITssMealFeeService;
import com.rybbaby.tss.front.tssMemberAddSubtractRecord.service.ITssMemberAddSubtractRecordService;
import com.rybbaby.tss.front.tssMemberAttendClassRecord.service.ITssMemberAttendClassRecordService;
import com.rybbaby.tss.front.tssMemberCheckAttendance.entity.ViewAttendanceDetails;
import com.rybbaby.tss.front.tssMemberCheckAttendance.service.ITssMemberCheckAttendanceService;
import com.rybbaby.tss.front.tssMemberFollowUpRecord.service.ITssMemberFollowUpRecordService;
import com.rybbaby.tss.front.tssMemberPackage.entity.TssMemberPackage;
import com.rybbaby.tss.front.tssMemberPackage.service.ITssMemberPackageService;
import com.rybbaby.tss.front.tssMemberReturnPremium.entity.ViewRefundDetails;
import com.rybbaby.tss.front.tssMemberReturnPremium.service.IViewRefundDetailsService;
import com.rybbaby.tss.front.tssMemberTurnHistoryRecord.entity.TssMemberTurnHistoryRecord;
import com.rybbaby.tss.front.tssMemberTurnHistoryRecord.service.ITssMemberTurnHistoryRecordService;
import com.rybbaby.tss.front.tssPackagePostpone.service.ITssPackagePostponeService;
import com.rybbaby.tss.front.tssPayment.entity.ViewPaymentDetails;
import com.rybbaby.tss.front.tssPayment.service.IViewPaymentDetailsService;
import com.rybbaby.tss.front.tssPertainRelation.entity.TssPertainRelation;
import com.rybbaby.tss.front.tssPertainRelation.service.ITssPertainRelationService;
import com.rybbaby.tss.front.tssRightStatistic.service.ITssRightStatisticService;
import com.rybbaby.tss.front.tssStudent.entity.TssStudent;
import com.rybbaby.tss.front.tssStudent.entity.TssStudentExport;
import com.rybbaby.tss.front.tssStudent.entity.ViewTssStudent;
import com.rybbaby.tss.front.tssStudent.service.ITssStudentService;
import com.rybbaby.tss.front.tssStudent.service.StudentExportService;
import com.rybbaby.tss.front.tssStudent.service.StudentImportService;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author 雷春琼
 * @description 客户表管理
 * @createDate 2017-08-09 下午2:48:34
 */
@Controller
@RequestMapping(value = "tssStudentController")
public class TssStudentController extends BaseController {

    @Autowired
    private ITssStudentService tssStudentService;
    @Autowired
    private ITssPertainRelationService tssPertainRelationService;
    @Autowired
    private ITssMemberCheckAttendanceService tssMemberCheckAttendanceService;
    @Autowired
    private ITssMemberPackageService tssMemberPackageService;
    @Autowired
    private IViewPaymentDetailsService viewPaymentDetailsService;

    @Autowired
    private IViewRefundDetailsService viewRefundDetailsService;
    @Autowired
    private ITssMemberAttendClassRecordService tssMemberAttendClassRecordService;
    @Autowired
    private ITssMemberAddSubtractRecordService tssMemberAddSubtractRecordService;
    @Autowired
    private ITssMemberFollowUpRecordService tssMemberFollowUpRecordService;
    @Autowired
    private ITssPackagePostponeService tssPackagePostponeService;
    @Autowired
    private ITssRightStatisticService tssRightStatisticService;
    @Autowired
    private IViewService<ViewTssStudent> viewService;
    @Autowired
    private ITssMealFeeService tssMealFeeService;
    @Autowired
    private ITssMemberTurnHistoryRecordService tssMemberTurnHistoryRecordService;
    @Autowired
    private StudentImportService importService;
    @Autowired
    private StudentExportService studentExportService;
    @Autowired
    private ISysAdminUserService sysAdminUserService;
    @Autowired
    private ITssAllocationService tssAllocationService;


    /**
     * 获取客户表列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取客户表列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssStudentList", method = RequestMethod.POST)
    public ModelAndView tssStudentList(ViewTssStudent entity, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentListView"));
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            String ids = "";
            DetachedCriteria dc = DetachedCriteria.forClass(ViewTssStudent.class);
            //获取当前登录者
            String adminUserId = super.getLoginUser().getId();

            SysAdminUser sysAdminUser = this.sysAdminUserService.get(adminUserId);
            //获取当前登录者所拥有角色
            List<String> roleList = super.getLoginAdminRoles();

            if (roleList.contains(RoleConsts.TSS_COUNSELOR)) {

                dc.add(Restrictions.or(Restrictions.sqlRestriction(" ( listStatus = 1 and adminUserId ='" + adminUserId + "' )"),
                        Restrictions.sqlRestriction(" empAdminUserId ='" + adminUserId + "'")));

            } else {
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
            }
            /*//当前登录者为园长
            if (roleList.contains(RoleConsts.TSS_ROLE_KINDERGARTEN_LEADER)||){
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
            }
            //当前登录者为顾问主管
            if(roleList.contains(RoleConsts.TSS_COUNSELOR_DIRECTOR)){
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
            }
            //当前登录者为顾问
            if (roleList.contains(RoleConsts.TSS_COUNSELOR)){
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + adminUserId + "') "));
            }
            //当前登录者为财务不做任何处理
            if(roleList.contains(RoleConsts.TSS_FINANCE)){
            }
            //当前登录者为教务
            if (roleList.contains(RoleConsts.TSS_TEACHING_AFFAIRS)){
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + adminUserId + "') "));
            }
            //当前登录者为教学主管不做任何处理
            if(roleList.contains(RoleConsts.TSS_TEACHING_DIRECTOR)){
            }
            //当前登录者为教师
            if (roleList.contains(RoleConsts.TSS_TEACHER)){
            }*/
            dc.add(Restrictions.eq("isMember", false));
            dc.addOrder(Order.desc("updateTime"));
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = viewService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }


    /**
     * 查询用户
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "查询用户", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "findStudentByName", method = RequestMethod.GET)
    public String findStudentByName(TssStudent entity) {
       /*	AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
			Map<String , String []> unLockMap = getParameterMap(request);
			DetachedCriteria dc = DetachedCriteria.forClass(SysAdminUser.class);
			HqlGenerateUtil.fillDetachedCriteria(dc , entity , unLockMap);
			dc.add(Restrictions.eq("duty",duty));
			List<SysAdminUser> empSysAdminUserList=this.empSysAdminUserService.findByDetached(dc);
			ajr.setData(empSysAdminUserList.toArray());
		} catch (Exception e) {
			throw e;
		}
		return ajr.jsonResponse(true);*/
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            List<TssStudent> TssStudent = this.tssStudentService.findStudentByName(entity.getName());
            ajr.setData(TssStudent.toArray());
        } catch (Exception e) {
            //throw e;
            e.printStackTrace();
        }
        return ajr.jsonResponse(true);
    }

    /**
     * 转到编辑视图
     *
     * @param entity       接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到客户表视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(TssStudent entity, @RequestParam(required = true) String serializeNum, @RequestParam(required = false, defaultValue = "0") Integer type) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentEditView"));
        List<TssPertainRelation> relationList = new ArrayList<>();
        if (entity != null && entity.getId() != null) {
            TssStudent editEntity = this.tssStudentService.get(entity.getId());
            relationList = tssPertainRelationService.findBySql(editEntity.getId());
            mav.addObject("editEntity", editEntity);
            mav.addObject("relationList", relationList);
            mav.addObject("editModel", "edit");
        } else {
            mav.addObject("relationList", relationList);
            mav.addObject("editModel", "add");
        }
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("memberType", type);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 保存编辑的对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存客户表对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(TssStudent entity) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {

            String adminUserId = super.getLoginUser().getId();
            ajr.setResMsg("保存成功!");
            String pertainRelationList = request.getParameter("pertainRelationList");
            boolean bool = this.tssStudentService.saveOrUpdate(adminUserId, pertainRelationList, entity);
            if (!bool) {
                ajr.setResCode(301);
                ajr.setResMsg("保存失败!");
            } else {
                ajr.setResCode(200);
                ajr.setResMsg("保存成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 根据用户id修改会员状态,会员转历史以及恢复历史
     *
     * @param serializeNum
     * @param targetDataId
     * @param status
     * @return
     */
    @ResponseBody
    @RequestLog(content = "会员转历史以及恢复历史", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "updateStatus", method = RequestMethod.POST)
    public String delete(@RequestParam(required = true) String serializeNum, @RequestParam(required = true) String targetDataId, @RequestParam(required = true) String handleContent, @RequestParam(required = true) Integer status) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        String adminUserId = super.getLoginUser().getId();
        try {
            //转历史生成权责
            if (status == 6) {
                //查询课时包
                List<TssMemberPackage> list = tssMemberPackageService.findByMemberId(targetDataId);
                HashMap<String, Object> map = new HashMap<>();
                for (TssMemberPackage memberPackage : list) {
                    //转历史课时包权责
                    Double nowUnitPrice = memberPackage.getNowUnitPrice();
                    map.put("nowUnitPrice", nowUnitPrice);
                    map.put("memberId", targetDataId);
                    if (memberPackage.getType() == 1) {
                        Integer surplusFormalClassHour = memberPackage.getSurplusFormalClassHour();
                        Integer surplusPresentClassHour = memberPackage.getSurplusPresentClassHour();
                        map.put("stuType", memberPackage.getType());
                        map.put("surplusFormalClassHour", surplusFormalClassHour);
                        map.put("surplusPresentClassHour", surplusPresentClassHour);
                    }
                    if (memberPackage.getType() == 2) {
                        Integer surplusFormalAttendanceDay = memberPackage.getSurplusFormalAttendanceDay();
                        Integer surplusPresentAttendanceDay = memberPackage.getSurplusPresentAttendanceDay();
                        map.put("stuType", memberPackage.getType());
                        map.put("surplusFormalAttendanceDay", surplusFormalAttendanceDay);
                        map.put("surplusPresentAttendanceDay", surplusPresentAttendanceDay);
                    }
                    boolean c = tssRightStatisticService.saveOrUpdateTssRightStatisticService(null, map, adminUserId, 7, 13, 0, null);
                    //转历史餐点费权责
                    TssMealFee tssMealFee = tssMealFeeService.findByStuId(targetDataId);
                    if (tssMealFee != null) {
                        map.put("amount", (tssMealFee.getSurplusAmout() == null ? 0 : tssMealFee.getSurplusAmout()));
                        map.put("consumptionAmount", (tssMealFee.getConsumptionAmount() == null ? 0 : tssMealFee.getConsumptionAmount()));
                        boolean d = tssRightStatisticService.saveOrUpdateTssRightStatisticService(null, map, adminUserId, 7, 16, 0, null);
                    }

                    //保存转历史操作记录
                    TssMemberTurnHistoryRecord tssMemberTurnHistoryRecord = new TssMemberTurnHistoryRecord();
                    tssMemberTurnHistoryRecord.setMemberId(targetDataId);
                    tssMemberTurnHistoryRecord.setAdminUserId(adminUserId);
                    tssMemberTurnHistoryRecord.setHandleMatter(3);
                    if(tssMealFee!=null){
                        String HandleContent = "剩余餐点费" + (tssMealFee.getSurplusAmout() == null ? 0 : tssMealFee.getSurplusAmout());
                    }
                    tssMemberTurnHistoryRecord.setHandleContent("会员转历史");
                    tssMemberTurnHistoryRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    tssMemberTurnHistoryRecord.setVersion(0);
                    Serializable saveId = tssMemberTurnHistoryRecordService.saveEntity(tssMemberTurnHistoryRecord);
                    memberPackage.setAdminUserId(adminUserId);
                    tssMemberPackageService.clearMemberPackagerCountCorrelation(memberPackage);
                }
            }
            Integer tssStuId = tssStudentService.updateParameterById(ImmutableMap.of(("stuStatus"), status), targetDataId);
            TssMemberTurnHistoryRecord entity = new TssMemberTurnHistoryRecord();
            entity.setAdminUserId(adminUserId);
            entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
            entity.setHandleContent(handleContent);
            entity.setMemberId(targetDataId);
            if (status == 6) {
                //转历史
                entity.setHandleMatter(1);
            } else {
                //恢复
                entity.setHandleMatter(2);
            }
            Serializable newId = this.tssMemberTurnHistoryRecordService.save(entity);
            if (tssStuId > 0 && newId != null) {
                ajr.setResCode(200);
                ajr.setResMsg("更新成功!");
            } else {
                ajr.setResCode(302);
                ajr.setResMsg("更新失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                boolean batchDelete = this.tssStudentService.batchDelete(ids.split(","));
                if (!batchDelete) {
                    ajr.setResMsg("删除失败!");
                    ajr.setResCode(302);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                this.tssStudentService.deleteEntityById(id);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }


    /**
     * 根据id查询会员详情
     *
     * @param serializeNum
     * @param memberId
     * @param type
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestLog(content = "根据id查询会员详情", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getMemberDetailById", method = RequestMethod.GET)
    public ModelAndView getMemberDetailById(@RequestParam(required = true) String serializeNum, @RequestParam(required = true) String memberId, @RequestParam(required = false) Integer type, @RequestParam(required = false) Integer flag) throws Exception {
        ModelAndView mav = null;
        try {
            switch (flag) {
                case 1:
                    if (type == 1 || type == 0) {
                        //亲子会员详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentDetailView"));
                    } else if (type == 2) {
                        //过渡会员详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitStudentDetailView"));
                    }
                    Map<String, Object> studentDetailById = this.tssStudentService.getStudentDetailById(memberId);
                    mav.addObject("data", studentDetailById);
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    mav.addObject("serializeNum", serializeNum);
                    mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
                    break;
                case 2:
                    if (type == 1) {
                        //亲子会员课时包详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentPackageDetailView"));
                    } else if (type == 2) {
                        //过渡会员课时包班级详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitStudentPackageDetailView"));
                    }
                    List<Map<String, Object>> memberPackagesList = this.tssMemberPackageService.getListByMemberId(memberId, type);
                    mav.addObject("memberPackagesList", memberPackagesList);
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    break;
                case 3:
                    if (type == 1) {
                        //亲子会员班级详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentClassDetailView"));
                    } else if (type == 2) {
                        //过渡会员班级详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitStudentClassDetailView"));
                    }
                    List<Map<String, Object>> attentLessonlistMap = this.tssMemberAttendClassRecordService.getAttendClassLessonsDetailList(memberId, type);
                    mav.addObject("attentLessonlistMap", attentLessonlistMap);
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    break;
                case 4:
                    if (type == 1) {
                        //亲子会员考勤详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentAttendanceDetailView"));
                    } else if (type == 2) {
                        //过渡会员考勤详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitStudentAttendanceDetailView"));
                    }
                    ViewAttendanceDetails entity = new ViewAttendanceDetails();
                    entity.setMemberId(memberId);
                    Map<String, String[]> unLockMap = getParameterMap(request);
                    DetachedCriteria dc = DetachedCriteria.forClass(ViewAttendanceDetails.class);
                    HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
                    PageBean pageBean = tssMemberCheckAttendanceService.pageList(dc, 1, 10);
                    mav.addObject(super.SEARCH_MAP, unLockMap);
                    mav.addObject(super.PAGE_BEAN, pageBean);
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    break;
                case 5:
                    if (type == 1) {
                        //亲子会员加减课时详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentAddsubtractDetailView"));
                    } else if (type == 2) {
                        //过渡会员加减课时详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitStudentAddsubtractDetailView"));
                    }
                    List<Map<String, Object>> addSbustractMapList = this.tssMemberAddSubtractRecordService.getDetailListBymemberId(memberId, type);
                    mav.addObject("addSbustractMapList", addSbustractMapList);
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    break;
                case 6:
                    if (type == 1 || type == 0) {
                        //亲子会员收款详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentReceivablesDetailView"));
                    } else if (type == 2) {
                        //过渡会员收款详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitStudentReceivablesDetailView"));
                    }
                    ViewPaymentDetails payment = new ViewPaymentDetails();
                    payment.setStuId(memberId);
                    Map<String, Object> map = this.viewPaymentDetailsService.getPaymentListByMemberId(payment);
                    mav.addObject("packageDetailsList", map.get("packageDetailsList"));
                    mav.addObject("DepositDetailsList", map.get("DepositDetailsList"));
                    mav.addObject("otherPaymentDetailsList", map.get("otherPaymentDetailsList"));
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    break;
                case 7:
                    if (type == 1 || type == 0) {
                        //亲子会员退款详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentRefundDetailView"));
                    } else if (type == 2) {
                        //过渡会员退款详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitStudentRefundDetailView"));
                    }
                    //退费记录
                    List<ViewRefundDetails> viewRefundDetailsList = viewRefundDetailsService.viewRefundDetailsList(memberId);
                    mav.addObject("viewRefundDetailsList", viewRefundDetailsList);
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    break;
                case 8:
                    if (type == 1 || type == 0) {
                        //亲子会员跟进记录列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentFollowUpDetailView"));
                    } else if (type == 2) {
                        //过渡会员跟进记录列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitStudentFollowUpDetailView"));
                    }
                    List<Map<String, Object>> followUpMapList = this.tssMemberFollowUpRecordService.getDetailListByMemberId(memberId, type);
                    mav.addObject("followUpMapList", followUpMapList);
                    mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    break;
                case 9:
                    if (type == 1) {
                        //亲子会员转历史详情记录列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssStudentHistoryDetailView"));
                    } else if (type == 2) {
                        //过渡会员转历史详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitStudentHistoryDetailView"));
                    }
                    List<Map<String, Object>> turnHistoryMapList = this.tssMemberTurnHistoryRecordService.getDetailListByMemberId(memberId, type);
                    mav.addObject("turnHistoryMapList", turnHistoryMapList);
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    break;
                case 10:
                    if (type == 1) {
                        //亲子会员延期详情记录列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssPackagePostponeDetailListView"));
                    } else if (type == 2) {
                        //过渡会员延期详情列表
                        mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitPackagePostponeDetailListView"));
                    }
                    List<Map<String, Object>> postoneMapList = this.tssPackagePostponeService.getDetailListByMemberId(memberId, type);
                    mav.addObject("postoneMapList", postoneMapList);
                    mav.addObject("memberId", memberId);
                    mav.addObject("packageType", type);
                    break;
                case 11:
                    mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssAllocationListView"));
                    List<Map<String, Object>> detailListByMemberId = this.tssAllocationService.getDetailListByMemberId(memberId);
                    mav.addObject("detailListByMemberId", detailListByMemberId);
                    mav.addObject("memberId", memberId);
                    break;
            }
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @RequestLog(content = "转到客户表视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "Jump", method = RequestMethod.GET)
    public ModelAndView Jump(TssStudent entity) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("JumpView"));

        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }


    /**
     * 根据ids导出excle
     *
     * @param ids 需要导出的id字符串
     * @throws Exception
     */
    @RequestMapping("/exportExcle")
    @ResponseBody
    public void exportExcle(TssStudentExport entity, PageBean paramPageBean, @RequestParam(required = true) String ids, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String flag = request.getParameter("flag");
        String path = "modelExcel/客户导入模板.xlsx";
        String templateName = request.getParameter("templateName");
        List<TssStudentExport> tssStudents = null;
        List<String> stuIdList = null;
        /**
         * 优先判断是否选择序号（ids）
         * 如果序号未选择 当标识符为 1 的时候 根据标识条件导出 标识为 0 时 默认导出所有数据
         * */
        if (ids == "") {
            if (flag.equals("1")) {
                Map<String, String[]> unLockMap = getParameterMap(request);
                DetachedCriteria dc = DetachedCriteria.forClass(TssStudentExport.class);
                HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
                PageBean pageBean = tssStudentService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
                tssStudents = (List<TssStudentExport>) pageBean.getList();
            } else {
                tssStudents = studentExportService.getAllList();
            }
        }
        //如果选择了序号 则根据序号导出该信息
        if (ids != "") {
            String[] idss = ids.split(",");
            stuIdList = Arrays.asList(idss);
            tssStudents = this.studentExportService.getStudentListById(stuIdList);
        }

        ExportUtil e = new ExportUtil();
        e.export(path, templateName, tssStudents, request, response);
    }


    /**
     * 校验新增决策人手机号是否已存在
     *
     * @param contractPhone 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "校验新增决策人手机号是否已存在", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "checkPhoneIsSame", method = RequestMethod.GET)
    public String checkPhoneIsSame(@RequestParam(required = true) String contractPhone, @RequestParam(required = true) String name) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String schoolId = super.getLoginUser().getSchoolId();

            Boolean b = this.tssStudentService.findBycontractPhone(contractPhone, schoolId, name);
            if (!b) {
                ajr.setResCode(301);
                ajr.setResMsg("客户已存在,不可成为新用户!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ajr.jsonResponse(true);
    }

    /**
     * 预览
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @CrossOrigin
    @RequestMapping("/importPreview")
    @ResponseBody
    public String importPreview(HttpServletRequest request, HttpServletResponse response) {
        String adminUserId = super.getLoginUser().getId();
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        ajr.setResMsg("加载成功!");
        StringBuffer stringBuffer = new StringBuffer();
        try {
            List<Map<String, Object>> errorList = importService.importPreview(request);

            Map<String, Object> replyMap = new HashMap<>();

            List<Map<String, Object>> errorsList = new ArrayList<Map<String, Object>>();
            Map<String, Object> errorMap = new HashMap<>();
            if (errorList.size() > 0) {
                for (Map<String, Object> map : errorList) {
                    String error = (String) map.get("error");
                    if (error != null) {
                        ajr.setResMsg(error);
                        ajr.setResCode(301);
                    } else {
                        errorsList.add(map);
                    }
                }
            }
            replyMap.put("list", errorsList);

            ajr.setData(replyMap);

        } catch (Exception e) {
            e.printStackTrace();
        }

        //response.setCharacterEncoding("UTF-8");
        //response.getWriter().print(stringBuffer);
        return ajr.jsonResponse(true);
    }

    /**
     * 客户管理>客户名单>导入功能
     * 杨然
     * 最新修改时间：2017年11月21日14:30:12
     */
    @CrossOrigin
    @RequestMapping("/importStudent")
    @ResponseBody
    public String importStudent(HttpServletRequest request, HttpServletResponse response) {
        String adminUserId = super.getLoginUser().getId();
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        ajr.setResMsg("保存成功!");
        StringBuffer stringBuffer = new StringBuffer();
        try {
            List<Map<String, Object>> errorList = importService.stuImport(request, adminUserId);

            Map<String, Object> replyMap = new HashMap<>();

            List<Map<String, Object>> errorsList = new ArrayList<Map<String, Object>>();
            Map<String, Object> errorMap = new HashMap<>();
            if (errorList.size() > 0) {

                for (Map<String, Object> map : errorList) {
                    String error = (String) map.get("error");
                    Integer errorSize = (Integer) map.get("errorSize");
                    Integer successSize = (Integer) map.get("successSize");
                    String suffix = (String) map.get("suffix");
                    if (error != null) {
                        ajr.setResMsg(error);
                        ajr.setResCode(301);
                    } else if (errorSize != null || successSize != null) {
                        if (errorSize > 0) {
                            ajr.setResCode(201);
                            ajr.setResMsg("部分导入成功!");
                        } else {
                            ajr.setResCode(200);
                            ajr.setResMsg("导入成功!");
                        }
                        errorMap.put("errorSize", errorSize);
                        errorMap.put("successSize", successSize);
                    } else if (suffix != null) {
                        errorMap.put("suffix", suffix);
                    } else {
                        errorsList.add(map);
                    }
                }
            }
            replyMap.put("list", errorsList);
            replyMap.put("map", errorMap);

            ajr.setData(replyMap);
            HttpSession session = getSession();
            session.setAttribute("errorsList", errorsList);

        } catch (Exception e) {
            e.printStackTrace();
        }

        //response.setCharacterEncoding("UTF-8");
        //response.getWriter().print(stringBuffer);
        return ajr.jsonResponse(true);
    }

    @RequestMapping("/errorExportExcle")
    @ResponseBody
    public void errorExportExcle(HttpServletResponse response, HttpServletRequest request) {
        String suffix = request.getParameter("suffix");
        System.out.println(suffix);
        try {
            String[] headers = {"幼儿姓名", "幼儿昵称", "幼儿性别", "出生日期", "妈妈（电话）", "妈妈（姓名）", "决策人/监护人", "爸爸（电话）", "爸爸（姓名）", "决策人/监护人",};

            List<Map<String, Object>> errorsList = (List<Map<String, Object>>) getSession().getAttribute("errorsList");
            if (errorsList.size() > 0) {
                importService.exportListMap(suffix, headers, errorsList, request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/templateExcle")
    @ResponseBody
    public void templateExcle(HttpServletResponse response, HttpServletRequest request) {
        try {
            String path = "modelExcel/客户导入模板.xlsx";

            URL resource = this.getClass().getClassLoader().getResource("/modelExcel/客户导入模板.xlsx  ");
            URL resource1 = this.getClass().getClassLoader().getResource("WEB-INF/xlsx/客户导入模板.xlsx");
            URL resource2 = this.getClass().getClassLoader().getResource("客户导入模板.xlsx");
            URL resource3 = TssStudentController.class.getResource("src/main/resources/jso/客户导入模板.xlsx");
            URL resource4 = TssStudentController.class.getResource("jso/客户导入模板.xlsx");
            URL url = TssStudentController.class.getClassLoader().getResource("jso/客户导入模板.xlsx");

            ExportUtil e = new ExportUtil();
            e.export("jso/export_student.json", "11", null, request, response);

            // InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/WEB-INF/xlsx/客户导入模板.xlsx");
            InputStream inputStream1 = this.getClass().getClassLoader().getResourceAsStream("WEB-INF/xlsx/客户导入模板.xlsx");
            // File file = File.createTempFile(SequenceUtil.getLowerCaseUUID(), null);
            //  FileUtils.copyInputStreamToFile(inputStream, file);
            // IOUtils.closeQuietly(inputStream);

            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            File file = new File(resource1.toURI());

            FileInputStream fileInputStream = new FileInputStream(file);

            int len = 0;
            byte[] buffer = new byte[1024];


            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("客户导入模板.xlsx", StandardCharsets.UTF_8.toString()));
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(buffer, 0, len);
            while ((len = fileInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);//将缓冲区的数据输出到客户端浏览器
            }
            fileInputStream.close();
            IOUtils.closeQuietly(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
